package models.cms;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.persistence.*;

import models.sys.User;
import play.db.jpa.Model;

/**
 *
 * 帖子
 */
@Entity(name = "t_post")
public class Post extends Model {

    public static final int STATE_DELETED = 9;
    public static final int STATE_NORMAL = 0;
    public static final int STATE_DRAFT = 1;

    public String subject;
    @Column(length = 2048)
    public String summary;
    @Column
    @Lob
    public String content;

    public String images;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "resoures_id", nullable = true)
    public List<Resource> resources;
    public String author;
    @ManyToOne
    public User user;

    public Date created_at;

    public String tags_text;
    @ManyToMany
    public Set<Tag> tags;

    public int cnt_view;
    public int cnt_voteup;
    public int cnt_favorite;
    public int cnt_follow;
    public int cnt_reply;
    public int cnt_report;

    //0 normal, 9 delete
    public int state;

    @ManyToOne
    public Post to_post;

    public List<Post> load_replies() {
        return Post.find("to_post=?", this).fetch();
    }
    public List<Comment> load_comments() {
        return Comment.find("to_post=?",this).fetch();
    }
    public List<Comment> load_top_comments() {
        return Comment.find("to_post=? and to_comment is null",this).fetch();
    }
    public PostUserState load_user_state(User user) {
        PostUserState postUserState = PostUserState.find("post = ? and user = ?", this, user).first();
        if(postUserState == null ){
            postUserState = new PostUserState();
            postUserState.post = this;
            postUserState.user = user;
        }
        return postUserState;
    }
    public List<Post> load_related_posts() {
        Query query = Post.em().createQuery("select p from models.cms.Post p " +
                "join p.tags t " +
                "where p != :self and p.to_post is null and t.name in (:tags) order by p.created_at desc");
        query.setParameter("self", this);
        query.setParameter("tags", tags.stream().map(t->t.name).collect(Collectors.toList()));
        query.setMaxResults(5);
        return query.getResultList();
    }
}
